import * as TYPES from '../actions/actionTypes';
import o from '../components/o';
import Toast from 'react-native-root-toast'
import { fetchToken } from './LoginAction'
export function loadMore(api, params) {
    return (dispatch, getState) => {
        const { dataList, hasMore, loading } = getState().Checks;

        const { token } = getState().User;
        const { pageNum, keyword, pageSize, filter ,orderByDesc} = params;
        const skip = (pageNum - 1) * pageSize
        dispatch({ type: TYPES.INVERTORY_GETDATA_ING });
        const _api = api + "?token=" + token;
        if (filter) {
            o(_api).take(pageSize).skip(skip).filter(filter).inlineCount().orderByDesc(orderByDesc).get().then(oHandler => {
                dispatch(loadMoreSuccess(oHandler, params, dataList))
            }).fail((e) => {
                dispatch(loadMoreFail(e, TYPES.INVERTORY_GETDATA_FAIL))
            })
        } else {
            o(api).take(pageSize).skip(skip).inlineCount().orderByDesc(orderByDesc).get().then(oHandler => {
                dispatch(loadMoreSuccess(oHandler, params, dataList))
            }).fail((e) => {
                dispatch(loadMoreFail(e, TYPES.INVERTORY_GETDATA_FAIL))
            })
        }
    }
}
export function loadMoreSuccess(oHandler, params, dataList) {
    const { data, inlinecount } = oHandler;
    const { pageNum, pageSize, keyword } = params;
    let preData = dataList ? dataList : [];
    if (pageNum * pageSize < inlinecount) {
        return { type: TYPES.INVERTORY_GETDATA_SUCCESS, dataList: preData.concat(data), pageNum: pageNum, hasMore: true, keyword: keyword }
    } else {
        return { type: TYPES.INVERTORY_GETDATA_SUCCESS, dataList: preData.concat(data), pageNum: pageNum, hasMore: false, keyword: keyword }
    }
}

export function loadMoreFail(e, type, msg) {
    if (e.msg == "token invalid.") {
        Toast.show("验证失效，正在为您重新获取", {
            duration: Toast.durations.LONG,
            position: Toast.positions.CENTER,
        })
        dispatch(fetchToken())//这里让他跳转主界面吧
    } else {
        const message = msg ? msg : "获取数据异常"
        Toast.show(message, {
            duration: Toast.durations.LONG,
            position: Toast.positions.CENTER,
        })
        return { type: type }
    }
}

export function search(keyword) {
    return (dispatch => { dispatch({ type: SEARCH_INPUT, keyword: keyword }) })
}

// export function loadMoreSuccess(oHandler, params, dataList) {
//     const {pageNum, pageSize} = params;
//     const {data, inlineCount} = oHandler;
//     let preData = dataList ? dataList : [];

//     if (pageNum * pageSize < inlineCount) {
//         return { type: TYPES.INVERTORY_GETDATA_SUCCESS, dataList: preData.concat(data), pageNum: pageNum, hasMore: true, keyword: keyword }
//     } else {
//         return { type: TYPES.INVERTORY_GETDATA_SUCCESS, dataList: preData.concat(data), pageNum: pageNum, hasMore: false, keyword: keyword }
//     }
// }
export function initialData(params) {
    return (dispatch) => {
        const data = JSON.parse(params);
        dispatch({ type: TYPES.INVERTORY_DETAIL_INITIAL, data: data })
    }

}

export function resultInitialData(params) {
    return (dispatch) => {
        dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_INITIAL, data: params })
    }
}

//状态和盘点id对应下的商品id
export function resultGetGoods() {
    return (dispatch, getState) => {
        dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_ING })
        const { InventoryId, item } = getState().Result;
        const { token } = getState().User;
        let params = {
            filter: "InventoryId eq " + InventoryId + " and store_type eq " + item.state
        }
        const _api = "erp_storehouse?token=" + token
        o(_api).filter(params.filter).get().then(oHandler => {
            const data = oHandler.data
            console.log(data)
            if (data && data.length > 0) {
                dispatch(filterGoods(data))
            }
        }).catch(e => {
            dispatch(loadMoreFail(e, TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_FAIL), "商品获取异常")
        })
    }

}
//获取商品列表
function filterGoods(res) {
    return (dispatch, getState) => {
        let filter = ''
        for (let i = 0; i < res.length; i++) {
            if (filter) {
                filter = filter + " or Archives_ID eq " + res[i].GoodId
            } else {
                filter = "Archives_ID eq " + res[i].GoodId
            }
        }
        let params = {
            filter: filter,
            select: "Name,Archives_ID,Code,State",
            expand: "archives_goods($filter=State eq 1),archives_storehouse,archives_file",
        }
        const { token } = getState().User;
        const api = "erp_archivess?token=" + token;
        o(api).select(params.select).filter(params.filter).expand(params.expand).get().then(oHandler => {
            //处理goodList  goods长度是在库数 storehouse长度是盘点数  storehouse对应状态的长度是对应状态数
            const data = oHandler.data
            console.log(data)
            dispatch(handlerGoodList(data));
        }).catch(e => {
            dispatch(loadMoreFail(e, TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_FAIL), "商品详情获取异常")
        })
    }

}
//处理数据
function handlerGoodList(res) {
    return (dispatch, getState) => {
        const { InventoryId, item } = getState().Result
        for (let i = 0; i < res.length; i++) {
            let stocks = 0,//在库数
                invNumber = 0,//盘点数
                serialList = [];//对应状态序列号
            const goodsSerails = res[i].archives_goods;
            for (let k = 0; k < goodsSerails.length; k++) {
                if (goodsSerails[k].State == 1) {
                    stocks++
                }
            }
            const storehouse = res[i].archives_storehouse;
            for (let j = 0; j < storehouse.length; j++) {
                if (storehouse[j].InventoryId == InventoryId) {
                    invNumber++
                    if (storehouse[j].store_type == item.state) {
                        serialList.push(storehouse[j])
                    }
                }
            }
            res[i]['stocks'] = stocks;
            res[i]['invNumber'] = invNumber;
            res[i]['count'] = serialList.length;
            res[i]['serialList'] = serialList;
            res[i].images = res[i].archives_file.Url.split(',')
        }
        console.log(res)
        dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_SUCCESS, dataList: res })
    }
}


export function fetchSerails(params) {
    return (dispatch, getState) => {
        const { api, filter, select } = params;
        let params = {
            $filter: "InventoryId eq " + InventoryId + " and store_type eq " + item.state,
            $select: "BarCode"
        }
        const { token } = getState().User;
        const _api = api + "?token=" + token;
        o(_api).select(select).filter(filter).get().then(oHandler => {
            dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_SUCCESS, data: oHandler })
        }).catch(e => {
            dispatch(loadMoreFail(e, TYPES.TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_FAIL, "未知序列号获取异常"))
        })
    }
}
export function resultSetailInitial(params) {
    return (dispatch) => {
        dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_SERIAL_INITIAL, data: params })
    }
}


//添加盘点后
export function unshiftInventroy(params) {
    return (dispatch, getState) => {
        const dataList_old = getState().Checks.dataList;
        let dataList = dataList_old && dataList_old.length > 0 ? [].concat[dataList_old] : [];
        dataList = dataList ? dataList : [];
        dataList.unshift(params);
        dispatch({ type: TYPES.INVENTORY_DATA_UNSHIFT, dataList: dataList })
    }
}

//odata4规范后使用
export function resultGetGoodsOnready() {
    if (item.state != 3) {
        let filter = "erp_storehouse/any(x: x/InventoryId eq " + InventoryId + ") and erp_storehouse/any(x: x/store_type eq " + item.state + ")",
            select = "Name,Archives_ID,Code,State",
            expand = "erp_goodss($select=BarCode),erp_goodss($filter=State eq 1 ),erp_storehouse($select=store_type,BarCode),erp_storehouse($filter=InventoryId eq " + InventoryId + ")";
        // $expand: "erp_goodss/$count($filter=State eq 1 ),erp_storehouse/$count($filter=InventoryId eq "+InventoryId+")"
        o(api).filter(filter).select(select).expand(expand).then((oHandler) => {
            //处理goodList  goods长度是在库数 storehouse长度是盘点数  storehouse对应状态的长度是对应状态数
            dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_SUCCESS, dataList: dataList })
        })
    } else {
        let
            filter = "InventoryId eq " + InventoryId + " and store_type eq " + item.state,
            select = "BarCode"

        o(api).filter(filter).select(select).then((oHandler) => {
            console.log(res)
            dispatch({ type: TYPES.INVERTORY_DETAIL_RESULT_GETGOODS_SUCCESS, dataList: dataList })
        })
    }
}